
import { useEffect, useState } from 'react';
import { ScrollView, Text, View } from '@tarojs/components';
import Taro, { useDidShow } from '@tarojs/taro';
import { Cascader, Elevator, Menu, Overlay, Pagination, Input } from '@nutui/nutui-react-taro';
import getLocation from '@/lib/getLocation';
import IndexFooterBar from '@/components/IndexFooterBar';
import { setActivePage } from '@/store/userDataSlice';
import { useDispatch, useSelector } from 'react-redux';
import { setCinemaList } from '../../store/cinemaListSlice';

import './cinema.scss';
import CinemaCard from './components/CinemaCard';
import CinemaCardSkeleton from './components/CinemaCardSkeleton';




type resultdata = { title: string, list: cityTypeList[]; };
type cityTypeList = { name: string, id: number; };

const Cinema = () => {
    const [isGetLocation, setIsGetLocation] = useState<boolean>(true);
    const dispatch = useDispatch();
    const movieData = useSelector((state: any) => state.movieData);
    const cinemaList = useSelector((state: any) => state.cinemaList);
    const [thisPageCinemaList, setThisPageCinemaList] = useState([]);
    const [searchInput, setSearchInput] = useState();
    const [userCity, setUserCity] = useState({ nm: "定位中", id: 0 });
    const [isSelectCity, setIsSelectCity] = useState(false);
    const [resortdata, setResortdata] = useState<resultdata[]>();
    const [options, setOptions] = useState<{ text: string, value: number; }[]>([
        { text: "全城", value: 0, },
        { text: "加载中", value: -1 },
    ]);
    const [isScroll, setIsScroll] = useState(false);
    const cinemaCity = movieData.cinemaCity;

    //函数根据城市名称返回城市id
    const searchCityId = (cityName) => {

        if (!cinemaCity || !cinemaCity.cts) {
            console.log('城市数据未加载完成', cinemaCity);
            return;
        }
        const citydata = cinemaCity.cts;
        let id;
        for (let j = 0; j < citydata.length; j++) {
            if (cityName === citydata[j].nm) {
                id = citydata[j].id;
                break;
            }
        }
        return id;
    };

    //设置当前页面footbar为active
    const useData = useSelector((state: any) => state.userData);

    useDidShow(() => {
        dispatch(setActivePage("电影院"));
        console.log(useData);
    });

    //获取影院列表
    useEffect(() => {
        getLocation((location) => {
            if (!location) return;
            console.log("打印location", location);
            Taro.request({
                url: `https://apis.netstart.cn/maoyan/index/moreCinemas?offset=0&limit=9999&cityId=${userCity.id}&lat=${location.latitude}&lng=${location.longitude}`,
                success: function (res) {
                    setThisPageCinemaList(res.data);
                    dispatch(setCinemaList(res.data));
                }
            });
        });
    }, [userCity.id]);

    //获取并坐标，并设置用户所在城市
    useEffect(() => {
        getLocation((location) => {
            if (location.latitude === 0 && location.longitude === 0) {
                alert("获取位置失败,请手动选择城市");
                setIsGetLocation(false);
                setUserCity({ nm: "定位失败", id: 0 });
                console.log(isGetLocation);
                return;
            }
            console.log(location);
            Taro.request({
                url: `https://apis.netstart.cn/maoyan/city/latlng?lat=${location.latitude}&lng=${location.longitude}`,
                success: function (res) {
                    console.log(res.data);
                    if (res.data.error) {
                        setUserCity({ nm: "北京", id: 1 });
                        return;
                    }
                    const cityName = res.data.data.city;
                    const id = searchCityId(cityName);
                    setUserCity({ nm: cityName, id: id });
                }
            });
        });
    }, []);

    //设置影院分类
    useEffect(() => {
        Taro.request({
            url: `https://apis.netstart.cn/maoyan/index/filterCinemas?ci=${userCity.id}`,
            success: function (res) {
                if (res.data && res.data.district) {
                    const newFilterCinemas = res.data.district;
                    const option: { text: string, value: number; }[] = [];
                    if (newFilterCinemas) {
                        newFilterCinemas.subItems.forEach((item, index) => {

                            option.push({ text: item.name, value: index });
                            option[0].text = "全城";
                            setOptions(option);
                        });
                    }
                }

            }
        });
    }, [userCity.id]);

    //获取设置所有城市列表
    useEffect(() => {
        if (!cinemaCity) return;
        //城市数据转换为NUTUI的Elevator需要的数据格式        
        const curresortdata: resultdata[] = [];
        let list: cityTypeList[] = [];
        let startwith = "";
        console.log("打印城市影院列表", cinemaCity);
        const hotCity = cinemaCity.hot;
        const citydata = cinemaCity.cts;
        const hotCityList: cityTypeList[] = [];
        for (let i = 0; i < hotCity.length; i++) {
            const id = searchCityId(hotCity[i]);
            hotCityList.push({ name: hotCity[i], id: id });
        }
        curresortdata.push({ title: "热", list: hotCityList });

        const rescitydata = [...citydata].sort((a, b) => {
            if (a.py > b.py) {
                return 1;
            } else {
                return -1;
            }
        });
        console.log(rescitydata);

        for (let i = 0; i < rescitydata.length; i++) {
            if (startwith != rescitydata[i].py[0]) {
                startwith = rescitydata[i].py[0];
                // console.log(startwith);
            }
            list.push({ name: rescitydata[i].nm, id: rescitydata[i].id });
            if ((rescitydata[i + 1] && rescitydata[i + 1].py[0] != startwith) || i === rescitydata.length - 1) {
                curresortdata.push({ title: startwith, list: list });
                list = [];
            }
        }
        setResortdata(curresortdata);
    }, [cinemaCity]);

    const onItemClick = (key: string, item: any) => {
        setUserCity({ nm: item.name, id: item.id });
        setIsSelectCity(false);
        console.log(key, item); // 打印选中的城市名称和id
    };

    const handleSearchChange = (inputValue) => {
        const prevCinemaList = cinemaList.cinemaList;
        const searchText = inputValue;
        setThisPageCinemaList(prevCinemaList.filter((item: { title: string, location: string; }, index) => {
            return item.title.indexOf(searchText) !== -1 || item.location.indexOf(searchText) !== -1;
        }));
        console.log("thispage", thisPageCinemaList);
        console.log(searchText);
    };
    console.log("thisPageCinemaList", thisPageCinemaList);

    return (
        <View className='cinemaContainer'>

            {isSelectCity &&
                <View style={{ position: "fixed", zIndex: "9999", width: "100vw" }}>
                    <Elevator onItemClick={(key: string, item: any) => onItemClick(key, item)} list={resortdata} sticky height='100vh' />
                </View>
            }
            <View style={{ display: "flex", justifyContent: "space-between" }}>
                <Text className='cinemaContainer-location' onClick={() => setIsSelectCity(true)}>城市：{userCity.nm ? userCity.nm : "定位中...可点击手动定位"}</Text>

                <Input value={searchInput} placeholder='请输入搜索内容...' style={{ border: "10px blod black" }} onChange={handleSearchChange} />
            </View>

            <Menu onOpen={() => setIsScroll(true)} onClose={() => { setIsScroll(false); }} >

                <Menu.Item options={options} defaultValue={0} onChange={(val) => {
                    console.log(val);
                }}
                />
                <Menu.Item options={[
                    { text: '距离近', value: 0 },
                    { text: '价格低', value: 1 },
                ]} defaultValue={0} onChange={(val) => { console.log(val); }}
                />
                <Menu.Item options={[
                    { text: '筛选', value: 0 },
                    { text: '条件1', value: 1 },
                    { text: '条件2', value: 2 },
                ]} defaultValue={0} onChange={(val) => { console.log(val); }}
                />

            </Menu>
            {/* <div style={{ height: `${Taro.getWindowInfo().windowHeight - 230}px`, overflowY: isScroll ? "hidden" : "auto" }}> */}
            <View>
                {thisPageCinemaList.length !== 0 ? thisPageCinemaList.map((item, index) =>
                    <CinemaCard key={index} isGetLocation={isGetLocation} props={item} />
                ) : Array(6).fill(null).map((_, index) => <CinemaCardSkeleton key={index} />)}
            </View>
            <IndexFooterBar />
        </View>
    );
};

export default Cinema;
